package elements

import (
	"strconv"
	"yizhuoyan/go-study/pdfgo/handyio"
)

type CrossReferenceSubsection struct {
	firstObjectNumber int                    `#:"第一个对象的编号"`
	entryList         []*CrossReferenceEntry `#:"所有entry"`
	entryMap          map[uint32]*CrossReferenceEntry
}

func (this *CrossReferenceSubsection) GetEntry(objNum int) *CrossReferenceEntry {
	for i, one := range this.entryList {
		if this.firstObjectNumber+i == objNum {
			return one
		}
	}
	return nil
}
func (this *CrossReferenceSubsection) WriteSubsection(w handyio.PdfRawWriter) error {
	w.WriteBytes([]byte(strconv.FormatInt(int64(this.firstObjectNumber), 10)))
	w.WriteByte(' ')
	w.WriteBytes([]byte(strconv.FormatInt(int64(len(this.entryList)), 10)))
	w.WriteByte('\n')
	for _, one := range this.entryList {
		if err := one.WriteEntry(w); err != nil {
			return err
		}
	}
	return nil
}

func (this *CrossReferenceSubsection) ReadSubsection(r handyio.PdfRawReader) error {
	startAt := r.IndexCurrent()
	firstONBytes := r.NextBytesUntilWhiteSpace()
	firstON, err := strconv.ParseInt(string(firstONBytes), 10, 64)
	if err != nil {
		_ = r.IndexMoveTo(startAt)
		return r.NotSupport("非数字")
	}
	this.firstObjectNumber = int(firstON)
	r.SkipNextWhiteSpaces()
	entryCountBytes := r.NextBytesUntilWhiteSpace()
	entryCount, err := strconv.ParseInt(string(entryCountBytes), 10, 64)
	if err != nil {
		_ = r.IndexMoveTo(startAt)
		return r.NotSupport("非数字")
	}
	r.SkipNextWhiteSpaces()
	var entries = make([]*CrossReferenceEntry, entryCount)

	for i := 0; i < int(entryCount); i++ {
		var one = new(CrossReferenceEntry)
		if err = one.ReadEntry(r); err != nil {
			_ = r.IndexMoveTo(startAt)
			return err
		}
		entries[i] = one
	}
	this.entryList = entries
	return nil
}
